package com.youko.backstage.web.commodity;

import com.youko.backstage.bean.commodity.*;
import com.youko.backstage.dto.commodity.*;
import com.youko.backstage.dto.merchant.ResponseDto;
import com.youko.backstage.mapper.commodity.PicturePathMapper;
import com.youko.backstage.service.commodity.CommodityCategoryService;
import com.youko.backstage.service.commodity.CommoditySkuService;
import com.youko.backstage.service.commodity.CommoditySkuSpecValueService;
import com.youko.backstage.service.commodity.CommoditySpuService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author: youko
 * @classname: CommoditySpuController
 * @Description: some desc
 * @date: 2022/7/6 8:56
 */
@RestController
public class CommoditySpuController {
    @Value("${SavePath.ProfilePhoto}")
    private String ProfilePhotoSavePath;   //图标图片存储路径
    @Value("${SavePath.ProfilePhotoMapper}")
    private String ProfilePhotoMapperPath;   //图标映射路径

    @Autowired
    CommoditySpuService commoditySpuService;

    @Autowired
    CommoditySkuService commoditySkuService;

    @Autowired
    CommoditySkuSpecValueService commoditySkuSpecValueService;

    @Autowired
    CommodityCategoryService commodityCategoryService;

    @Autowired
    PicturePathMapper picturePathMapper;


    /**
     * 新增Spu以及Sku
     * @param commoditySpuRequest
     * @return
     */
    @PostMapping("/merchant/spu/insert")
    public InsertResponseDto insertSpu(@RequestBody CommoditySpuRequest commoditySpuRequest){
        CommoditySpu commoditySpu=new CommoditySpu();
        commoditySpu.setGoodsName(commoditySpuRequest.getGoodsName());
        commoditySpu.setLowPrice(commoditySpuRequest.getLowPrice());
        commoditySpu.setCategoryId(commodityCategoryService.selectCategoryByName(commoditySpuRequest.getCategory()).getId());

        int spuId = commoditySpuService.insertCommoditySpu(commoditySpu);

        List<CommoditySpecValueRequest> commoditySpecValueRequests = commoditySpuRequest.getCommoditySpecValueRequests();
        for (CommoditySpecValueRequest csvr:commoditySpecValueRequests){
            String[] values = csvr.getValues();
            String spec = csvr.getSpec();
            CommoditySpec commoditySpec=new CommoditySpec();
            commoditySpec.setSpecName(spec);
            int specId = commoditySpuService.insertSpec(commoditySpec, values);
            commoditySpuService.insertSpuSpec(spuId,specId);
        }



        //获取根据Sku的规格属性插入SkuSpecValue
        List<CommoditySkuSpecValueRequest> commoditySkuSpecValueRequests = commoditySpuRequest.getCommoditySkuSpecValueRequests();
        for (CommoditySkuSpecValueRequest cssvr:commoditySkuSpecValueRequests){
            CommoditySku commoditySku=new CommoditySku();
            commoditySku.setPrice(cssvr.getPrice());
            commoditySku.setSkuName(commoditySpu.getGoodsName()+" "+cssvr.getSpecValue1()+" "+cssvr.getSpecValue2());
            commoditySku.setSpuId(spuId);
            commoditySku.setShopId(commoditySpuRequest.getShopId());
            int skuId = commoditySkuService.insertSku(commoditySku);
            //spu拥有的全部SpecValue
            List<CommoditySpecValue> specValues = commoditySpuService.getSpecValues(spuId);

            for (CommoditySpecValue csv:specValues){
                CommoditySkuSpecValue commoditySkuSpecValue=new CommoditySkuSpecValue();
                if (csv.getSpecValue().equals(cssvr.getSpecValue1())||csv.getSpecValue().equals(cssvr.getSpecValue2())){
                    commoditySkuSpecValue.setSpecValueId(csv.getId());
                    commoditySkuSpecValue.setSkuId(skuId);
                    commoditySkuSpecValueService.insertSkuSpecValue(commoditySkuSpecValue);
                }
            }
        }

        InsertResponseDto insertResponseDto=new InsertResponseDto();
        insertResponseDto.setStatus(1);
        insertResponseDto.setMsg("操作成功");
        insertResponseDto.setSpuId(spuId);

        return insertResponseDto;
    }

    /**
     * 返回所有三级分类
     */
    @GetMapping("merchant/spu/category3")
    public List<CommodityCategory> selectAllCategory3(){
        return commodityCategoryService.selectAllCategory3();
    }


    /**
     * 插入图片
     */
    @PostMapping("/spu/profilePhotoUpload")
    public String profilePhotoUpload(@RequestParam int spuId,@RequestParam int mainPagePic, @RequestParam("file") MultipartFile fileUpload){
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句，规定特定格式的图片才能上传，否则拒绝保存。
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //为了避免发生图片替换，这里使用了文件名重新生成
        fileName = UUID.randomUUID()+suffixName;
        PicturePath picturePath=new PicturePath();
        try {
            //将图片保存到文件夹里
            fileUpload.transferTo(new File(ProfilePhotoSavePath+fileName));
            picturePath.setPicPath(ProfilePhotoMapperPath+fileName);
            picturePath.setSpuId(spuId);
            picturePath.setMainPagePic(mainPagePic);
            commoditySpuService.insertPicturePath(picturePath);
            return ProfilePhotoMapperPath+fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 显示所有的spu根据shopid
     */
    @GetMapping("/merchant/spu/selectSpuByShop")
    public List<SpuResponseDto> selectSpuByShop(@Param("shopId") int shopId){
        List<SpuResponseDto> spuList=new ArrayList<>();
        int[] spuIds = commoditySkuService.selectSpuByShop(shopId);
        for (int i=0;i<spuIds.length;i++){
            SpuResponseDto spuResponseDto=new SpuResponseDto();
            if(commoditySpuService.selectSpuById(spuIds[i])!=null){
                spuResponseDto.setSpu(commoditySpuService.selectSpuById(spuIds[i]));
                List<PicturePath> picturePaths = picturePathMapper.selectPicturePathBySpuId(spuIds[i]);
                for (PicturePath picturePath:picturePaths){
                    if(picturePath.getMainPagePic()==1){
                        spuResponseDto.setPicPath(picturePath.getPicPath());
                    }
                }
                spuList.add(spuResponseDto);
            }
        }
        return spuList;
    }

    /**
     * 根据spuId删除spu
     */
    @RequestMapping("/merchant/spu/deleteSpu")
    public String deleteSpu(int spuId){
        commoditySpuService.deleteSpu(spuId);
        return "删除成功";
    }




}
